<template>
  <div class="debug-panel">
    <el-card title="调试面板" style="margin: 20px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>🔧 系统调试面板</span>
          <el-button size="small" type="danger" @click="visible = false">关闭</el-button>
        </div>
      </template>

      <el-space direction="vertical" style="width: 100%;">
        <!-- 数据库连接测试 -->
        <el-card>
          <template #header>
            <span>📊 数据库连接测试</span>
          </template>
          <el-space>
            <el-button @click="testDbConnection" :loading="loading.dbConnection">测试连接</el-button>
            <el-button @click="checkAdminTable" :loading="loading.adminTable">检查admin表</el-button>
            <el-button @click="checkAdminData" :loading="loading.adminData">检查admin数据</el-button>
          </el-space>
        </el-card>

        <!-- 认证调试 -->
        <el-card>
          <template #header>
            <span>🔐 认证调试</span>
          </template>
          <el-space>
            <el-button @click="checkAdminUser" :loading="loading.adminUser">检查admin用户</el-button>
            <el-button @click="listAdmins" :loading="loading.listAdmins">列出所有admin</el-button>
            <el-button @click="checkAuthStatus" :loading="loading.authStatus">检查登录状态</el-button>
          </el-space>
        </el-card>

        <!-- 日志输出 -->
        <el-card>
          <template #header>
            <span>📝 调试日志</span>
          </template>
          <el-button @click="clearLogs" size="small" type="info" style="margin-bottom: 10px;">清空日志</el-button>
          <el-input
            v-model="logContent"
            type="textarea"
            :rows="10"
            readonly
            placeholder="调试信息将显示在这里..."
          />
        </el-card>

        <!-- 快速操作 -->
        <el-card>
          <template #header>
            <span>⚡ 快速操作</span>
          </template>
          <el-space direction="vertical" style="width: 100%;">
            <el-button @click="runAllTests" type="primary" :loading="loading.allTests">运行所有测试</el-button>
            <el-button @click="openBackendLog" type="info">打开后端日志</el-button>
            <el-text size="small" type="info">
              提示：后端端口已修改为 8765，请确保后端服务已启动
            </el-text>
          </el-space>
        </el-card>
      </el-space>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'

const visible = ref(true)
const logContent = ref('')

const loading = reactive({
  dbConnection: false,
  adminTable: false,
  adminData: false,
  adminUser: false,
  listAdmins: false,
  authStatus: false,
  allTests: false
})

const addLog = (message, type = 'info') => {
  const timestamp = new Date().toLocaleTimeString()
  const prefix = type === 'error' ? '❌' : type === 'success' ? '✅' : type === 'warning' ? '⚠️' : 'ℹ️'
  logContent.value += `[${timestamp}] ${prefix} ${message}\n`

  // 自动滚动到底部
  setTimeout(() => {
    const textarea = document.querySelector('.el-textarea__inner')
    if (textarea) {
      textarea.scrollTop = textarea.scrollHeight
    }
  }, 100)
}

const testDbConnection = async () => {
  loading.dbConnection = true
  addLog('开始测试数据库连接...')

  try {
    const response = await request.get('/debug/db-connection')
    addLog(`数据库连接成功: ${response.data}`, 'success')
  } catch (error) {
    addLog(`数据库连接失败: ${error.message}`, 'error')
  } finally {
    loading.dbConnection = false
  }
}

const checkAdminTable = async () => {
  loading.adminTable = true
  addLog('检查admin表结构...')

  try {
    const response = await request.get('/debug/check-admin-table')
    addLog('admin表结构检查成功:', 'success')
    addLog(response.data)
  } catch (error) {
    addLog(`检查admin表失败: ${error.message}`, 'error')
  } finally {
    loading.adminTable = false
  }
}

const checkAdminData = async () => {
  loading.adminData = true
  addLog('检查admin表数据...')

  try {
    const response = await request.get('/debug/check-admin-data')
    addLog('admin表数据检查成功:', 'success')
    addLog(response.data)
  } catch (error) {
    addLog(`检查admin数据失败: ${error.message}`, 'error')
  } finally {
    loading.adminData = false
  }
}

const checkAdminUser = async () => {
  loading.adminUser = true
  addLog('检查admin用户是否存在...')

  try {
    const response = await request.get('/auth/check-admin')
    addLog(`admin用户检查结果: ${response.data}`, 'success')
  } catch (error) {
    addLog(`检查admin用户失败: ${error.message}`, 'error')
  } finally {
    loading.adminUser = false
  }
}

const listAdmins = async () => {
  loading.listAdmins = true
  addLog('获取所有admin用户...')

  try {
    const response = await request.get('/auth/list-admins')
    addLog(`找到 ${response.data.length} 个admin用户:`, 'success')
    response.data.forEach(admin => {
      addLog(`  - ID: ${admin.id}, 用户名: ${admin.username}, 创建时间: ${admin.createdAt}`)
    })
  } catch (error) {
    addLog(`获取admin用户列表失败: ${error.message}`, 'error')
  } finally {
    loading.listAdmins = false
  }
}

const checkAuthStatus = async () => {
  loading.authStatus = true
  addLog('检查当前登录状态...')

  try {
    const response = await request.get('/auth/status')
    addLog(`登录状态: ${response.data ? '已登录' : '未登录'}`, response.data ? 'success' : 'warning')
  } catch (error) {
    addLog(`检查登录状态失败: ${error.message}`, 'error')
  } finally {
    loading.authStatus = false
  }
}

const runAllTests = async () => {
  loading.allTests = true
  addLog('🚀 开始运行所有调试测试...', 'info')

  try {
    await testDbConnection()
    await new Promise(resolve => setTimeout(resolve, 500))

    await checkAdminTable()
    await new Promise(resolve => setTimeout(resolve, 500))

    await checkAdminData()
    await new Promise(resolve => setTimeout(resolve, 500))

    await checkAdminUser()
    await new Promise(resolve => setTimeout(resolve, 500))

    await listAdmins()
    await new Promise(resolve => setTimeout(resolve, 500))

    await checkAuthStatus()

    addLog('🎉 所有测试完成！', 'success')
  } catch (error) {
    addLog(`批量测试过程中出现错误: ${error.message}`, 'error')
  } finally {
    loading.allTests = false
  }
}

const clearLogs = () => {
  logContent.value = ''
  addLog('日志已清空')
}

const openBackendLog = () => {
  addLog('请查看后端控制台输出获取详细日志信息')
  addLog('或在后端项目目录运行: tail -f logs/application.log')
}
</script>

<style scoped>
.debug-panel {
  max-width: 800px;
  margin: 0 auto;
}

.el-card {
  margin-bottom: 20px;
}

.el-textarea {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}
</style>